import { queryVehicleDetail } from '../../services/vehicle'
import { controlDoCommand, querySpaceGroupData, controlCommandResult, queryRealData } from '../../services/inspect'
import Toast from '@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    type:"",
    orderId:"",
    vehicleId:"",
    instId:"",
    spaceId:"",
    spaceVarId:"",
    vehicleInfo: {},
    weatherInfo:{
      airTemperature:33,
      humidity:66,
      pressure:88
    },
    cmdId:"",
    timer: null,
    url: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(!options){
      return
    }
    let type = options.type
    let orderId = options.orderId
    let vehicleId = options.vehicleId
    let instId = options.instId
    let spaceId = options.spaceId
    
    this.setData({
      type,
      orderId,
      vehicleId,
      instId,
      spaceId
    })
    if(vehicleId){
      this.getVehicleDetail(vehicleId)
    }
    if(spaceId){
      let typeUrl = ""
      if(type == 2){
        typeUrl = "ag"
      } else {
        typeUrl = "chargeRecord"
      }

      let queryData = {
        spaceId,
        url: typeUrl,
      }
      this.handleGetGroupVarId(queryData)
    }
  },

  onShow(){
    this.handleGetWeatherInfo()
  },

  onHide(){
    if(this.data.timer){
      clearInterval(this.data.timer)
    }
  },

  onUnload(){
    if(this.data.timer){
      clearInterval(this.data.timer)
    }
  },

  async getVehicleDetail(vehicleId){
    let res = await queryVehicleDetail(vehicleId)
    if(res.code === 200){
      let vehicleInfo = res.data
      this.setData({
        vehicleInfo
      })      
    }
  },

  handleReturn(){
    wx.navigateBack()
  },

  async handleGetGroupVarId(data){
    let resp = await querySpaceGroupData(data)
    console.log("resp>>>", resp)
    let spaceVarId = resp.rows[0].id
    console.log("spaceVarId>>>", spaceVarId)
    if(spaceVarId){
      this.setData({
        spaceVarId
      })
    }
  },

  // 随机数
  getUuid () {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
  },

  async handleControlDoCommand(){
    let cmdId = this.getUuid()
    let orderId = this.data.orderId
    let spaceId = this.data.spaceId
    let varId = this.data.spaceVarId
    let type = this.data.type
    let cutDownNum = 60
    this.setData({
      cmdId
    })
    let doCommandData = {
      cmdId,
      spaceId,
      varId,
      cmdType: "Cmd_RelayExecute",
      cmdValue: '1'
    }
    wx.setStorageSync(`${orderId}-${type}-doCommandData`, doCommandData)
    let resDoCommand = await controlDoCommand(doCommandData)
    if(resDoCommand.code == 200){
      wx.showLoading({
        title: '加载中',
      })
      this.handleSetInter(cutDownNum)
      this.handleGetCommandResult()
    }
  },

  async handleSetInter(cutDownNum){
    let cutNum = cutDownNum
    // if(this.data.timer){
    //   clearInterval(this.data.timer)
    // }
    const _this = this
    let timer = setInterval(function(){
      cutNum--
      _this.handleGetCommandResult()
      if(cutNum == 0){
        clearInterval(timer)
      }
    }, 1000)
    this.setData({
      timer
    })
  },

  async handleGetCommandResult(){
    let cmdId = this.data.cmdId
    let url = this.data.url
    let orderId = this.data.orderId
    let type = this.data.type
    let res = await controlCommandResult({cmdId})
    if(res.data && res.data.result){
      let commandResult = res.data.result
      if(commandResult == 'Cmd_Result_Success'){
        wx.setStorageSync(`${orderId}-${type}-yaokong`, true)
        wx.navigateTo({
          url,
        })
      } else if(commandResult == 'Cmd_Result_Fail') {
        Toast.fail('执行失败!')
      } else if(commandResult == 'Cmd_Result_TimeOut') {
        Toast.fail('执行超时!')
      }
      wx.hideLoading()
      if(this.data.timer){
        clearInterval(this.data.timer)
      }
    }
  },

  handleNext(){
    let url = ""
    let type = this.data.type
    let orderId = this.data.orderId
    let vehicleId = this.data.vehicleId
    let instId = this.data.instId
    let spaceId = this.data.spaceId
    if(type == 2){
      url = `/pages/inspect-insulation/inspect-insulation?orderId=${orderId}&vehicleId=${vehicleId}&instId=${instId}&spaceId=${spaceId}`
    } else if(type == 3){
      url = `/pages/inspect-charging/inspect-charging?orderId=${orderId}&vehicleId=${vehicleId}&instId=${instId}&spaceId=${spaceId}`
    } else if(type == 4){
      url = `/pages/inspect-discharge/inspect-discharge?orderId=${orderId}&vehicleId=${vehicleId}&instId=${instId}&spaceId=${spaceId}`
    } 

    if(!url) return
    this.setData({
      url
    })
    let ykIsOk = wx.getStorageSync(`${orderId}-${type}-yaokong`) || ""
    if(ykIsOk){
      wx.navigateTo({
        url,
      })
    } else {
      this.handleControlDoCommand()
    }

    wx.setStorageSync('weatherInfo', this.data.weatherInfo)
    
    // wx.navigateTo({
    //   url,
    // })
  },

  async handleGetWeatherInfo(){
    let queryData = ['1694160484276228098', '1694160484276228099', '1694160484276228100']
    let weatherRes = await queryRealData(queryData)
    console.log("weatherRes>>>", weatherRes)
    let weatherInfo = {
      airTemperature:33,
      humidity:66,
      pressure:88
    }
    if(weatherRes.data[0] && weatherRes.data[0]['value']){
      weatherInfo.airTemperature = weatherRes.data[0]['value']
    }

    if(weatherRes.data[1] && weatherRes.data[1]['value']){
      weatherInfo.humidity = weatherRes.data[1]['value']
    }

    if(weatherRes.data[2] && weatherRes.data[2]['value']){
      weatherInfo.pressure = weatherRes.data[2]['value']
    }

    this.setData({
      weatherInfo
    })
  }

})